﻿namespace Blaze.Editor.EditorExtensions
{
    using UnityEditor;
    using UnityEngine;

    /// <summary>
    /// 用于辅助初始化<see cref="ProjectWindowExtension"/>。
    /// </summary>
    [InitializeOnLoad]
    public class ProjectWindowExtensionInitializer
    {
        static ProjectWindowExtensionInitializer()
        {
            EditorApplication.update -= update;
            EditorApplication.update += update;

            EditorApplication.projectWindowItemOnGUI -= projectWindowItemOnGUIHandler;
            EditorApplication.projectWindowItemOnGUI += projectWindowItemOnGUIHandler;

            EditorApplication.projectChanged -= projectWindowChanged;
            EditorApplication.projectChanged += projectWindowChanged;

            Undo.undoRedoPerformed -= undoRedoPerformed;
            Undo.undoRedoPerformed += undoRedoPerformed;
        }

        private static void init()
        {
            if (mProjectWindow == null)
                mProjectWindow = new ProjectWindowExtension();
        }

        private static void projectWindowChanged()
        {
            init();
        }

        private static void projectWindowItemOnGUIHandler(string guid, Rect selectionRect)
        {
            init();
            mProjectWindow.ProjectWindowItemOnGUIHandler(guid, selectionRect);
        }

        static void undoRedoPerformed()
        {
            EditorApplication.RepaintProjectWindow();
        }

        private static void update()
        {
            init();
        }

        private static ProjectWindowExtension mProjectWindow;
    }
}